import tagpot, MySQLdb, string
cursor = tagpot.dbConnect()

def literal(val):
    if val:
        return MySQLdb.string_literal(val)   
    else:
        return "NULL"


def relation(anc, word):
    anc.strip()
    q = "select ko, en from anc where anchor ='%s'" % (anc)
    cursor.execute(q)
    REL = cursor.fetchall()
    #print q
    for r in REL:
        for i in r:
            s = i.split(",")
            for k in s:
                if k is '':
                    continue
                k=literal(k)
                q = "select num from rel where a = %s and b = %s" % (word.lower(), k.lower())
                cursor.execute(q)
                ok = cursor.fetchall()
                if (ok == ()):
                    num = 1
                    q = "insert into rel(a,b,num) values (%s,%s,%s)" % (word.lower(), k.lower(),num)
                    cursor.execute(q)
                else:
                    num = ok[0][0] + 1
                    q = "update rel SET num = %s WHERE a = %s and b = %s" % (num, word.lower(), k.lower())
                    cursor.execute(q)
if __name__=='__main__':
    q = "select word,anchor from word"
    cursor.execute(q)
    data = cursor.fetchall()
    for d in data:
        anc = d[1]
        AD = anc.split(",")
        for a in AD:
            if a is '': 
                continue
            relation(a,literal(d[0]))                        

                                
                    
                